<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: admin_templates.php,v $ : $Revision: 1.13 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}


if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}

require_once ("./includes/functions_html.php");
require_once ("./includes/functions_template.php");
$template->loadLanguageSection("templates");


/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Callback for parsing template group data
*/
function _templateGroupFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];
	
	$record["languageid"] = $_SWIFT["languagecache"][$record["languageid"]]["title"];
	$record["title"] = '<a href="index.php?_m=core&_a=managetemplates&tgroupid='. intval($record["tgroupid"]) .'">'. htmlspecialchars($record["title"]) .'</a>';

	$record["options"] = '<a href="index.php?_m=core&_a=managetemplates&tgroupid='. $record["tgroupid"] .'" title="'. $_SWIFT["language"]["templates"] .'"><img src="'. $_SWIFT["themepath"] .'icon_templates.gif" border="0">&nbsp;'. $_SWIFT["language"]["templates"] .'</a>&nbsp;&nbsp;&nbsp;<a href="index.php?_m=core&_a=edittemplategroup&tgroupid='. $record["tgroupid"] .'" title="'. $_SWIFT["language"]["settings"] .'"><img src="'. $_SWIFT["themepath"] .'icon_settings.gif" border="0">&nbsp;'. $_SWIFT["language"]["settings"] .'</a>&nbsp;&nbsp;&nbsp;<a href="javascript:doConfirm(\''. $_SWIFT["language"]["restoreconfirmask"] .'\', \'index.php?_m=core&_a=managetemplategroups&do=restore&tgroupid='. $record["tgroupid"] .'\');" title="'. $_SWIFT["language"]["restore"] .'"><img src="'. $_SWIFT["themepath"] .'icon_tgrouprestore.gif" border="0">&nbsp;'. $_SWIFT["language"]["restore"] .'</a>&nbsp;&nbsp;&nbsp;<a href="index.php?_m=core&_a=importexporttemplates&tgroupid='. $record["tgroupid"] .'&export=1" title="'. $_SWIFT["language"]["export"] .'"><img src="'. $_SWIFT["themepath"] .'icon_exportxml.gif" border="0">&nbsp;'. $_SWIFT["language"]["export"] .'</a>'. iif($record["ismaster"]==1, '&nbsp;&nbsp;&nbsp;&nbsp;<img src="'. $_SWIFT["themepath"] .'icon_deletedisabled.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=core&_a=managetemplategroups&do=delete&tgroupid='. $record["tgroupid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;');
	return $record;
}

/**
* Mass Action: Delete Template Groups
*/
function _maDeleteTemplateGroups()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]) || $_SWIFT["isdemo"] == true)
	{
		return false;
	}

	deleteGroups($_POST["itemid"]);
}






/**
* ###############################################
* IMPORT/EXPORT TEMPLATES
* ###############################################
*/
if ($eventaction == "importexporttemplates")
{
	require_once ("./includes/functions_xml.php");
	$xml = new XML();

	if ($_REQUEST["export"] == 1)
	{
		if (empty($_POST["exportoptions"]))
		{
			$_POST["exportoptions"] = EXPORT_ALL;
		}
		if (empty($_POST["filename"]))
		{
			$_POST["filename"] = generateTemplateFilename();
		}

		doExportTemplate($_REQUEST["tgroupid"], $_POST["exportoptions"], $_POST["filename"]);
		exit;
	} else if ($_REQUEST["import"] == 1) {
		// Check for successful upload
		if (file_exists($_FILES["templatefile"]["tmp_name"]) && $_SWIFT["isdemo"] != true)
		{
			// Success.. are we supposed to insert a new template group or merge changes with existing one..?
			if (!empty($_POST["tgroupid"]))
			{
				// Merge
				$result = updateTemplatesFromFile($_FILES["templatefile"]["tmp_name"], iif($_POST["ignoreversion"]=="1", false, true), $_POST["tgroupid"]);
				if ($result == -1)
				{
					$errormessage = $_SWIFT["language"]["versioncheckfailed"];
				} else {
					printRedirect(sprintf($_SWIFT["language"]["tgroupmergeconfirm"], $_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]["title"]), "index.php?_m=core&_a=managetemplategroups&mergetgroup=".urlencode($_REQUEST["tgroupid"]));
					exit;
				}
			} else {
				// Create New
				$result = importCreateNewGroup($_FILES["templatefile"]["tmp_name"], iif($_POST["ignoreversion"]=="1", false, true));
				if ($result == -1)
				{
					$errormessage = $_SWIFT["language"]["versioncheckfailed"];
				} else {
					printRedirect(sprintf($_SWIFT["language"]["tgroupnewimportconfirm"], $_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]["title"]), "index.php?_m=core&_a=edittemplategroup&tgroupid=".urlencode($result));
					exit;
				}
			}
		}
	}


	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["importexport"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=importexporttemplates" title="'.$_SWIFT["language"]["importexport"].'">'.$_SWIFT["language"]["importexport"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	// ======= EXPORT TEMPLATE GROUP =======
	printFormStart("exportform", "index.php", "POST", true);
	printMainTableHeader($_SWIFT["language"]["exporttemplates"]);

	$index = 0;
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["tgroupid"];
		$index++;
	}

	printSelectRow("tgroupid", $_SWIFT["language"]["exporttgroup"], $_SWIFT["language"]["desc_exporttgroup"], $options);
	printTextRow("filename", $_SWIFT["language"]["filename"], $_SWIFT["language"]["desc_filename"], "text", generateTemplateFilename());

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["exportalltemplates"];
	$options[0]["value"] = EXPORT_ALL;
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["exportmodifications"];
	$options[1]["value"] = EXPORT_MODIFICATIONS;

	printSelectRow("exportoptions", $_SWIFT["language"]["exportoptions"], $_SWIFT["language"]["desc_exportoptions"], $options);

	printSubmitRow($_SWIFT["language"]["exportxml"]);

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", "importexporttemplates");
	addHiddenField("export", "1");
	printFormEnd();


	// ======= IMPORT TEMPLATES =======
	echo "<BR />";
	printFormStart("importform", "index.php", "POST", true);
	printMainTableHeader($_SWIFT["language"]["importtemplates"]);

	printUploadRow("templatefile", $_SWIFT["language"]["templatefile"], $_SWIFT["language"]["desc_templatefile"]);

	$options[0]["title"] = $_SWIFT["language"]["createnewgroup"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["tgroupid"];
		$index++;
	}


	printSelectRow("tgroupid", $_SWIFT["language"]["mergewith"], $_SWIFT["language"]["desc_mergewith"], $options);

	printYesNoRow("ignoreversion", $_SWIFT["language"]["ignoreversion"], $_SWIFT["language"]["desc_ignoreversion"], iif(empty($_POST["ignoreversion"]), false, $_POST["ignoreversion"]));

	printSubmitRow($_SWIFT["language"]["importxml"]);

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", "importexporttemplates");
	addHiddenField("import", "1");
	printFormEnd();
	
	$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	$interface->adminFooter();







/**
* ###############################################
* INSERT NEW TEMPLATE GROUP
* ###############################################
*/
} else if ($eventaction == "inserttemplategroup") {
	if ($_POST["step"] == 1)
	{
		if (trim($_POST["title"]) == "" || trim($_POST["companyname"]) == "" || trim($_POST["languageid"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else if (trim($_POST["password"]) != "" && $_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
			$_POST["password"] = "";
			$_POST["passwordconfirm"] = "";
        } else if (!ereg('^[[:alnum:]]+$', $_POST["title"])) {
			$errormessage = $_SWIFT["language"]["invalidgrouptitle"];
		} else {
			// Do we have a template group with same name already?
			$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."templategroups` WHERE `title` = '". $dbCore->escape($_POST["title"]) ."';");
			if ($_total["totalitems"] > 0)
			{
				$errormessage = $_SWIFT["language"]["grouptitleexists"];
			} else {
				// Insert the template group
				$tgroupid = insertGroup($_POST["fromtgroupid"], $_POST["guestusergroupid"], $_POST["regusergroupid"], $_POST["title"], "", $_POST["companyname"], iif($_POST["enablepassword"]==1&&trim($_POST["password"])!="", $_POST["password"], ""), $_POST["languageid"], $_POST["restrictgroups"], $_POST["isdefault"], $_POST["loginapi_moduleid"], $_POST["departmentid"], $_POST["ticketstatusid"], $_POST["priorityid"]);

				printRedirect(sprintf($_SWIFT["language"]["groupinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managetemplategroups&inserttgroupid=".urlencode($tgroupid));
				exit;			
			}
		}
	}

	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["insertemplategroup"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplategroups" title="'.$_SWIFT["language"]["templategroups"].'">'.$_SWIFT["language"]["templategroups"].'</a> &raquo; <a href="index.php?_m=core&_a=inserttemplategroup" title="'.$_SWIFT["language"]["insertemplategroup"].'">'.$_SWIFT["language"]["insertemplategroup"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderTemplateGroupForm(INSERT);
	
	$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	$interface->adminFooter();





/**
* ###############################################
* MANAGE TEMPLATE GROUPS
* ###############################################
*/
} else if ($eventaction == "managetemplategroups") {
	if ($_GET["do"] == "delete" && $_GET["tgroupid"] != "" && isset($_SWIFT["tgroupcache"][$_GET["tgroupid"]]) && $_SWIFT["isdemo"] != true)
	{
		$infomessage = sprintf($_SWIFT["language"]["groupdelconfirm"], $_SWIFT["tgroupcache"][$_GET["tgroupid"]]["title"]);
		deleteGroups(array($_GET["tgroupid"]));
	} else if ($_GET["do"] == "restore" && $_GET["tgroupid"] != "" && isset($_SWIFT["tgroupcache"][$_GET["tgroupid"]]) && $_SWIFT["isdemo"] != true) {
		$infomessage = sprintf($_SWIFT["language"]["restoreconfirm"], $_SWIFT["tgroupcache"][$_GET["tgroupid"]]["title"]);
		restoreGroup($_GET["tgroupid"]);
	}
	

	if (trim($_REQUEST["inserttgroupid"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["groupinsertconfirm"], $_SWIFT["tgroupcache"][$_REQUEST["inserttgroupid"]]["title"]);
	} else if ($_REQUEST["updatetgroupid"] != "") {
		$infomessage = sprintf($_SWIFT["language"]["groupupdateconfirm"], $_SWIFT["tgroupcache"][$_REQUEST["updatetgroupid"]]["title"]);
	} else if (!empty($_REQUEST["mergetgroup"])) {
		$infomessage = sprintf($_SWIFT["language"]["tgroupmergeconfirm"], $_SWIFT["tgroupcache"][$_REQUEST["mergetgroup"]]["title"]);
	}
	
	

	$options["recordsperpage"] = "6";
	$options["sortby"] = "title";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteTemplateGroups";

	$options["idname"] = "tgroupid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["grouptitle"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'templategroups` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["companyname"];
	$options["advancedsearch"][1]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'templategroups` WHERE `companyname` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_templateGroupFields";

	$fields[0]["name"] = "title";
	$fields[0]["title"] = $_SWIFT["language"]["grouptitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "companyname";
	$fields[1]["title"] = $_SWIFT["language"]["companyname"];
	$fields[1]["width"] = "160";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "languageid";
	$fields[2]["title"] = $_SWIFT["language"]["glanguage"];
	$fields[2]["width"] = "140";
	$fields[2]["align"] = "center";

	$fields[3]["type"] = "custom";
	$fields[3]["name"] = "options";
	$fields[3]["title"] = $_SWIFT["language"]["options"];
	$fields[3]["width"] = "500";
	$fields[3]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["managegroups"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplategroups" title="'.$_SWIFT["language"]["managegroups"].'">'.$_SWIFT["language"]["managegroups"].'</a>', $_SWIFT["language"]["desc_templategroups"] , 0);
	printInfoBox($infomessage);

	$grid->start("templategroups", $_SWIFT["language"]["grouplist"], 'SELECT * FROM `'. TABLE_PREFIX .'templategroups` $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'templategroups`;', 'SELECT * FROM `'. TABLE_PREFIX .'templategroups` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	
	$grid->display("templategroups");
	$interface->adminFooter();	






/**
* ###############################################
* EDIT TEMPLATE GROUP
* ###############################################
*/
} else if ($eventaction == "edittemplategroup") {
	// Get the template group data
	$_tgroup = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templategroups` WHERE `tgroupid` = '". intval($_REQUEST["tgroupid"]) ."';");
	if (empty($_tgroup["tgroupid"]))
	{
		trigger_error($_SWIFT["language"]["invalidgroup"], E_USER_ERROR);
		exit;
	}

	if ($_POST["step"] == 1)
	{
		if (trim($_POST["title"]) == "" || trim($_POST["companyname"]) == "" || trim($_POST["languageid"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else if (trim($_POST["password"]) != "" && $_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
			$_POST["password"] = "";
			$_POST["passwordconfirm"] = "";
        } else if (!ereg('^[[:alnum:]]+$', $_POST["title"])) {
			$errormessage = $_SWIFT["language"]["invalidgrouptitle"];
		} else {
			// Do we have a template group with same name already?
			$_total["totalitems"] = 0;
			if ($_POST["title"] != $_tgroup["title"])
			{
				$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."templategroups` WHERE `title` = '". $dbCore->escape($_POST["title"]) ."';");				
			}
			if ($_total["totalitems"] > 0)
			{
				$errormessage = $_SWIFT["language"]["grouptitleexists"];
			} else {
				// Update the template group
				if ($_POST["enablepassword"] == 1 && md5($_POST["password"]) != $_tgroup["grouppassword"] && trim($_POST["password"]) != "")
				{
					// Password changed
					$finalpassword = $_POST["password"];
					$resetpw = true;
				} else if ($_POST["enablepassword"] == 0) {
					$finalpassword = "";
					$resetpw = true;
				} else if ($_POST["enablepassword"] == 1 && trim($_POST["password"]) == "") {
					// dont reset the pw
					$finalpassword = "";
					$resetpw = false;
				}
				
				updateGroup($_tgroup["tgroupid"], $_POST["guestusergroupid"], $_POST["regusergroupid"], $_POST["title"], "", $_POST["companyname"], $resetpw, $finalpassword, $_POST["languageid"], $_POST["restrictgroups"], $_POST["isdefault"], $_POST["loginapi_moduleid"], $_POST["departmentid"], $_POST["ticketstatusid"], $_POST["priorityid"]);

				printRedirect(sprintf($_SWIFT["language"]["groupupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managetemplategroups&updatetgroupid=".urlencode($_tgroup["tgroupid"]));
				exit;
			}
		}
	}

	$_POST = array_merge($_POST, $_tgroup);

	if (!empty($_tgroup["grouppassword"]))
	{
		$_POST["enablepassword"] = 1;
	}

	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["edittemplategroup"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplategroups" title="'.$_SWIFT["language"]["managegroups"].'">'.$_SWIFT["language"]["managegroups"].'</a> &raquo; <a href="index.php?_m=core&_a=edittemplategroup&tgroupid='. intval($_tgroup["tgroupid"]) .'" title="'.$_tgroup["title"].'">'.$_tgroup["title"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderTemplateGroupForm(EDIT);
	
	$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	$interface->adminFooter();






/**
* ###############################################
* MANAGE TEMPLATES
* ###############################################
*/
} else if ($eventaction == "managetemplates") {
	// If no template group is set, we display templates for master group
	if (empty($_REQUEST["tgroupid"]))
	{
		$_REQUEST["tgroupid"] = 1;
	}

	// Verify its a valid tgroup
	if (!isset($_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]))
	{
		trigger_error($_SWIFT["language"]["invalidgroup"], E_USER_ERROR);
	}

	if (!empty($_GET["templateupdate"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["templateupdateconfirm"], $_GET["templateupdate"]);
	} else if (!empty($_GET["templaterestore"])) {
		$infomessage = sprintf($_SWIFT["language"]["templaterestoreconfirm"], $_GET["templaterestore"]);		
	}
	

	$templatelist = array();
	// Build an array of all templates
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` = '". intval($_REQUEST["tgroupid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$templatelist[$dbCore->Record["tcategoryid"]][] = $dbCore->Record;
	}

	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["managetemplates"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);

	printInfoBox($infomessage);
	printErrorBox($errormessage);


	// ======= GROUP JUMP =======
	echo '<div id="groupjump" style="DISPLAY:none;">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["groupjump"]);

	$options = array();
	$index = 0;
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["tgroupid"];
		if ($val["tgroupid"] == $_REQUEST["tgroupid"])
		{
			$options[$index]["selected"] = true;
		}
		$index++;
	}
	printSelectRow("tgroupid", $_SWIFT["language"]["templategroup"], "", $options);
	printSubmitRow($_SWIFT["language"]["jump"]);
	printMainTableFooter();
	addHiddenField("_m", "core");
	addHiddenField("_a", "managetemplates");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;	
	

	printMainTableHeader(sprintf($_SWIFT["language"]["templatetitle"], $_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]["title"]));

	// ======= TOOLBAR OPTIONS =======
	echo '<tr>'.SWIFT_CRLF;
	echo '<td class="toolbarrow" align="left" colspan="2" valign="middle" nowrap><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="5"><img src="'. $_SWIFT["themepath"] .'grip.gif" border="0" /></td><td class="toolbarrow"><span class="toolbartext">&nbsp;<a href="javascript:switchDisplay(\'groupjump\');" id="white" title="'. $_SWIFT["language"]["groupjump"] .'">'. $_SWIFT["language"]["groupjump"] .'</a>&nbsp;|&nbsp;<a href="javascript:doCatExpand();" id="white" title="'. $_SWIFT["language"]["expandall"] .'">'. $_SWIFT["language"]["expandall"] .'</a></span></td></tr></table></td>'.SWIFT_CRLF;
	echo '</tr>'.SWIFT_CRLF;
	// ======= TOOLBAR OPTIONS =======

	$colarray[0]["align"] = "left";
	$colarray[0]["nowrap"] = true;
	$colarray[0]["value"] = $_SWIFT["language"]["templatecategories"];
	$colarray[0]["colspan"] = 2;
	printDataRow($colarray, "tabletitlerow");

	// Build the template category list
	$catidlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templatecategories` WHERE `tgroupid` = '". intval($_REQUEST["tgroupid"]) ."';");
	while ($dbCore->nextRecord())
	{
		if (!$module->isRegistered($dbCore->Record["module"]))
		{
			continue;
		}

		if (!empty($_SWIFT["language"][$dbCore->Record["name"]]))
		{
			$name = $_SWIFT["language"][$dbCore->Record["name"]];
		} else {
			$name = $dbCore->Record["name"];
		}

		if ($_REQUEST["tcategoryid"] == $dbCore->Record["tcategoryid"])
		{
			$displaystyle = "";
		} else {
			$displaystyle = "none";
		}

		$catidlist[] = $dbCore->Record["tcategoryid"];

		$colarray = array();
		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = '<a href="javascript:switchDisplay(\'cat'. $dbCore->Record["tcategoryid"] .'\');">'.$name."</a>";

		$colarray[1]["align"] = "center";
		$colarray[1]["nowrap"] = true;
		$colarray[1]["value"] = '<a href="javascript:switchDisplay(\'cat'. $dbCore->Record["tcategoryid"] .'\');"><img src="'. $_SWIFT["themepath"] .'icon_templateexpand.gif" border="0" />&nbsp;'.$_SWIFT["language"]["expand"] .'</a>';
		$colarray[1]["width"] = 150;

		printDataRow($colarray, getRowBG());
		$catclass = "row2";

		?><tr id="cat<?=$dbCore->Record["tcategoryid"]?>" bgcolor="#EBEBEB" style="DISPLAY: <?=$displaystyle?>;"><td colspan="2"><table width="100%"  border="0" cellpadding="1" cellspacing="0" bgcolor="#EDF4FF"><tr><td><table width="100%"  border="0" cellspacing="0" cellpadding="3"><?
		foreach ($templatelist[$dbCore->Record["tcategoryid"]] as $key=>$val)
		{
			if ($catclass == "row1")
			{
				$catclass = "row2";
			} else {
				$catclass = "row1";
			}
			?>
		  <tr class="<?=$catclass?>">
			<td width="10"><img src="<?
			echo $_SWIFT["themepath"];
			if ($val["modified"] == MODIFIED_NONE) {
				echo "icon_templatenotmodified.gif";
		} else if ($val["modified"] == MODIFIED_UPGRADE) {
				echo "icon_templateupgrade.gif";
		} else {
				echo "icon_templatemodified.gif";
		}
			?>"></td>
			<td><span class="smalltext"><a href="index.php?_m=core&_a=edittemplate&templateid=<?=$val["templateid"];?>"><?=htmlspecialchars($val["name"]);?></a> [<a href="index.php?_m=core&_a=edittemplate&templateid=<?=$val["templateid"];?>" target="_blank">&raquo;</a>]</span></td>
		  </tr>
			<?
		}
		?></td></tr></table></td></tr></table><?

		echo '<tr id="cat'. $dbCore->Record["tcategoryid"] .'" style="DISPLAY: none;"><td colspan="2">test</td></tr>'.SWIFT_CRLF;
	}

	?>
	<script language="Javascript">
		var catlist = new Array();
		<?
		for ($ii=0; $ii<count($catidlist); $ii++)
		{
			echo 'catlist['. $ii .'] = "cat'. $catidlist[$ii] .'";'.SWIFT_CRLF;
		}	
		?>

		function doCatExpand()
		{
			for (var ii=0; ii < catlist.length; ii++)
			{
				switchDisplay(catlist[ii]);
			}
		}
	</script>
	<?


	printMainTableFooter();

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .'<img src="'. $_SWIFT["themepath"] .'icon_templatenotmodified.gif" border="0" /> '. $_SWIFT["language"]["notmodified"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_templatemodified.gif" border="0" /> '. $_SWIFT["language"]["modified"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_templateupgrade.gif" border="0" /> '. $_SWIFT["language"]["upgrade"] .'&nbsp;&nbsp;&nbsp;</span>';

	$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	
	$interface->adminFooter();	







/**
* ###############################################
* EDIT A TEMPLATE
* ###############################################
*/
} else if ($eventaction == "edittemplate") {
	// Is the template group set? This is for the group jump code
	if (isset($_POST["tgroupid"]))
	{
		// Fetch the name of existing template..
		$_oldtemplate = $dbCore->queryFetch("SELECT `name`, `templateid` FROM `". TABLE_PREFIX ."templates` WHERE `templateid` = '". intval($_POST["templateid"]) ."';");
		if (empty($_oldtemplate["templateid"]))
		{
			// if this template id is empty we end the fetching right here..
			trigger_error($_SWIFT["language"]["invalidtemplate"], E_USER_ERROR);
		}

		// Ok, fetch the same template id from other group
		$_templateid = $dbCore->queryFetch("SELECT `templateid` FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` = '". intval($_REQUEST["tgroupid"]) ."' AND `name` = '". $dbCore->escape($_oldtemplate["name"]) ."';");
		if (empty($_templateid["templateid"]))
		{
			trigger_error($_SWIFT["language"]["invalidtemplate"], E_USER_ERROR);			
		}
		$_REQUEST["templateid"] = $_templateid["templateid"];
	}

	// Fetch the template
	$_template = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) WHERE templates.templateid = '". intval($_REQUEST["templateid"]) ."';");

	// Verify its a valid template
	if (empty($_template["templateid"]))
	{
		trigger_error($_SWIFT["language"]["invalidtemplate"], E_USER_ERROR);
	}


	// ======= PROCESS ACTIONS =======

	if ($_POST["action"] == $_SWIFT["language"]["savetemplate"] && $_SWIFT["isdemo"] != true)
	{
		// Save the template and redirect the user back over to the category list
		if ($_POST["contents"] != $_template["contents"])
		{
			updateTemplate($_template["templateid"], $_POST["contents"]);

			printRedirect(sprintf($_SWIFT["language"]["templateupdateconfirm"], $_template["name"]), "index.php?_m=core&_a=managetemplates&tcategoryid=".$_template["tcategoryid"]."&tgroupid=".$_template["tgroupid"]."&templateupdate=".urlencode($_template["name"]));
			exit;
		}
	} else if ($_POST["action"] == $_SWIFT["language"]["saveandreload"] && $_SWIFT["isdemo"] != true) {
		// Save the template and reload this page
		if ($_POST["contents"] != $_template["contents"])
		{
			updateTemplate($_template["templateid"], $_POST["contents"]);

			printRedirect(sprintf($_SWIFT["language"]["templateupdateconfirm"], $_template["name"]), "index.php?_m=core&_a=edittemplate&templateid=".$_template["templateid"]."&templateupdate=".urlencode($_template["name"]));
			exit;
		}
	} else if ($_POST["action"] == $_SWIFT["language"]["restore"] && $_SWIFT["isdemo"] != true) {
		restoreTemplate($_template["templateid"]);
		
		printRedirect(sprintf($_SWIFT["language"]["templateupdateconfirm"], $_template["name"]), "index.php?_m=core&_a=edittemplate&templateid=".$_template["templateid"]."&templaterestore=".urlencode($_template["name"]));
		exit;
	}
	
	
	// ======= END PROCESS ACTIONS =======

	if (!empty($_GET["templateupdate"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["templateupdateconfirm"], $_GET["templateupdate"]);
	} else if (!empty($_GET["templaterestore"])) {
		$infomessage = sprintf($_SWIFT["language"]["templaterestoreconfirm"], $_GET["templaterestore"]);		
	}


	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["managetemplates"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=edittemplate&templateid='. intval($_template["templateid"]) .'" title="'.$_template["name"].'">'.$_template["name"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	// ======= GROUP JUMP =======
	echo '<div id="groupjump" style="DISPLAY:none;">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["groupjump"]);
	$options = array();
	$index = 0;
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["tgroupid"];
		if ($val["tgroupid"] == $_template["tgroupid"])
		{
			$options[$index]["selected"] = true;
		}
		$index++;
	}
	printSelectRow("tgroupid", $_SWIFT["language"]["templategroup"], "", $options);
	printSubmitRow($_SWIFT["language"]["jump"]);
	printMainTableFooter();
	addHiddenField("templateid", $_template["templateid"]);
	addHiddenField("_m", "core");
	addHiddenField("_a", "edittemplate");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;	
	

	?>
	<script language="Javascript">
	<!--
	function highlightmetasearch() {
		document.tpledit.contents.select(); document.tpledit.contents.focus();
	}
	
	function copyToClipboard() {
		highlightmetasearch();
		if (browsercode == "IE" && (browserversion == "5" || browserversion == "6"))
		{
			textRange = document.tpledit.contents.createTextRange();
			textRange.execCommand("RemoveFormat");
			textRange.execCommand("Copy");
			alert("<?=$_SWIFT["language"]["clipboardconfirm"]?>");			
		} else {
			alert("<?=$_SWIFT["language"]["clipboardconfirmmoz"]?>");			
		}
   }

   function previewTemplate(templateid)
   {
		var screenHeight = window.screen.availHeight;
		var screenWidth = window.screen.availWidth;
		docWidth = (screenWidth/2)-250;
		docHeight = (screenHeight/2)-250;
		window.open("<?php echo $_SWIFT["swiftpath"];?>admin/index.php?_m=core&_a=previewtemplate&templateid="+templateid+"&randno="+doRand()+"&sessionid=<?=$_SWIFT["session"]["sessionid"]?>","previewtemplate"+doRand(), "toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=1,width=400,height=400,left="+docWidth+",top="+docHeight);
   }
	// --> 
	</script>
	<?

	printFormStart("tpledit");
	printMainTableHeader(sprintf($_SWIFT["language"]["edittemplatetitle"], $_template["name"], $_SWIFT["tgroupcache"][$_template["tgroupid"]]["title"]));

	// ======= TOOLBAR OPTIONS =======
	echo '<tr>'.SWIFT_CRLF;
	echo '<td class="toolbarrow" align="left" colspan="2" valign="middle" nowrap><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="5"><img src="'. $_SWIFT["themepath"] .'grip.gif" border="0" /></td><td class="toolbarrow"><span class="toolbartext">&nbsp;<a href="javascript:switchDisplay(\'groupjump\');" id="white" title="'. $_SWIFT["language"]["groupjump"] .'">'. $_SWIFT["language"]["groupjump"] .'</a>&nbsp;|&nbsp;<a href="javascript:copyToClipboard();" id="white" title="'. $_SWIFT["language"]["copyclipboard"] .'">'. $_SWIFT["language"]["copyclipboard"] .'</a>&nbsp;|&nbsp;<a href="javascript:previewTemplate(\''. $_template["templateid"] .'\');" id="white" title="'. $_SWIFT["language"]["preview"] .'">'. $_SWIFT["language"]["preview"] .'</a></span></td></tr></table></td>'.SWIFT_CRLF;
	echo '</tr>'.SWIFT_CRLF;
	// ======= TOOLBAR OPTIONS =======

	if ($_template["modified"] == MODIFIED_NONE)
	{
		$tstatus = sprintf($_SWIFT["language"]["tstatus"], $_SWIFT["themepath"]."icon_templatenotmodified.gif", $_SWIFT["language"]["notmodified"]);
	} else if ($_template["modified"] == MODIFIED_USER) {
		$tstatus = sprintf($_SWIFT["language"]["tstatus"], $_SWIFT["themepath"]."icon_templatemodified.gif", $_SWIFT["language"]["modified"]);		
	} else if ($_template["modified"] == MODIFIED_UPGRADE) {
		$tstatus = sprintf($_SWIFT["language"]["tstatus"], $_SWIFT["themepath"]."icon_templateupgrade.gif", $_SWIFT["language"]["upgrade"]);		
	}	
	
	printDefaultDescRow($_SWIFT["language"]["templatestatus"], $_SWIFT["language"]["desc_templatestatus"], $tstatus);

	printDefaultDescRow($_SWIFT["language"]["dateadded"], $_SWIFT["language"]["desc_dateadded"], edate($_SWIFT["settings"]["dt_datetimeformat"], $_template["dateline"]));

	printDescRow($_SWIFT["language"]["templatedata"]);

	$data = array();
	$data[0]["value"] = '<textarea style="WIDTH:100%;" name="contents" cols="100" rows="20">'. htmlspecialchars($_template["contents"]) .'</textarea>'.SWIFT_CRLF;
	$data[0]["align"] = "center";
	$data[0]["colspan"] = "2";

	printDataRow($data);

	$data = array();
	$data[0]["value"] = '<input type="submit" class="bluebuttonbig" name="action" value="'. $_SWIFT["language"]["savetemplate"] .'" />&nbsp;&nbsp;&nbsp;<input type="submit" class="yellowbuttonbigbig" name="action" value="'. $_SWIFT["language"]["saveandreload"] .'" />&nbsp;&nbsp;&nbsp;<input type="submit" class="yellowbuttonbig" name="action" value="'. $_SWIFT["language"]["restore"] .'" />'.SWIFT_CRLF;
	$data[0]["align"] = "center";
	$data[0]["colspan"] = "2";

	printDataRow($data);

	printMainTableFooter();
	addHiddenField("_m", "core");
	addHiddenField("_a", "edittemplate");
	addHiddenField("step", "1");
	addHiddenField("templateid", $_template["templateid"]);
	printFormEnd();

	$template->assign("backurl", "index.php?_m=core&_a=managetemplates&tcategoryid=".intval($_template["tcategoryid"])."&tgroupid=".intval($_template["tgroupid"]));
	
	$interface->adminFooter();


/**
* ###############################################
* PREVIEW TEMPLATE
* ###############################################
*/
} else if ($eventaction == "previewtemplate") {
	// Get the templateid
	$_template = $dbCore->queryFetch("SELECT `templateid`, `name`, `tgroupid` FROM `". TABLE_PREFIX ."templates` WHERE templateid = '". intval($_REQUEST["templateid"]) ."';");

	// Verify its a valid template
	if (empty($_template["templateid"]))
	{
		trigger_error($_SWIFT["language"]["invalidtemplate"], E_USER_ERROR);
	}

	$template->setGroup($_template["tgroupid"]);

	// Ok, now that we have the template. we just get smarty processed output for it.
	$result = $template->displayRawTemplate($_template["name"]);
	
	echo $result["status"];



/**
* ###############################################
* DIAGNOSTICS
* ###############################################
*/
} else if ($eventaction == "templatediagnostics") {


	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["diagnostics"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=templatediagnostics" title="'.$_SWIFT["language"]["diagnostics"].'">'.$_SWIFT["language"]["diagnostics"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	if ($_POST["listmodified"] == 1)
	{
		// List all modified templates
		printMainTableHeader(sprintf($_SWIFT["language"]["modifiedtemplates"], $_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]["title"]));

		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = $_SWIFT["language"]["templatename"];
		$colarray[1]["align"] = "center";
		$colarray[1]["nowrap"] = true;
		$colarray[1]["value"] = $_SWIFT["language"]["status"];
		printDataRow($colarray, "tabletitlerow");

		$dbCore->query("SELECT `templateid`, `name`, `modified` FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` = '". intval($_POST["tgroupid"]) ."' ORDER BY `templateid` ASC;");
		while ($dbCore->nextRecord())
		{
			if ($dbCore->Record["modified"] == MODIFIED_NONE) {
				$modifiedstatus = "icon_templatenotmodified.gif";
				$modifiedtext = $_SWIFT["language"]["notmodified"];
			} else if ($dbCore->Record["modified"] == MODIFIED_UPGRADE) {
				$modifiedstatus = "icon_templateupgrade.gif";
				$modifiedtext = $_SWIFT["language"]["upgrade"];
			} else {
				$modifiedstatus = "icon_templatemodified.gif";
				$modifiedtext = $_SWIFT["language"]["modified"];
			}

			if ($dbCore->Record["modified"] != MODIFIED_NONE)
			{
				$colarray = array();
				$colarray[0]["align"] = "left";
				$colarray[0]["nowrap"] = true;
				$colarray[0]["value"] = '<a href="'. $_SWIFT["swiftpath"] .'admin/index.php?_m=core&_a=edittemplate&templateid='. $dbCore->Record["templateid"] .'&tgroupid='. intval($_POST["tgroupid"]) .'">'.$dbCore->Record["name"]."</a>";


				$colarray[1]["align"] = "center";
				$colarray[1]["nowrap"] = true;
				$colarray[1]["value"] = '<img src="'. $_SWIFT["themepath"].$modifiedstatus .'" border="0" />&nbsp;'.$modifiedtext .'';
				$colarray[1]["width"] = 250;

				printDataRow($colarray, getRowBG());
			}
		}

		printMainTableFooter();

		echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .'<img src="'. $_SWIFT["themepath"] .'icon_templatemodified.gif" border="0" /> '. $_SWIFT["language"]["modified"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_templateupgrade.gif" border="0" /> '. $_SWIFT["language"]["upgrade"] .'&nbsp;&nbsp;&nbsp;';
		$template->assign("backurl", "index.php?_m=core&_a=templatediagnostics");
	} else if ($_POST["diagnose"] == 1) {
		// Diagnose smarty engine errors
		$template->setGroup($_POST["tgroupid"]);

		printMainTableHeader(sprintf($_SWIFT["language"]["diagnoseerrors"], $_SWIFT["tgroupcache"][$_REQUEST["tgroupid"]]["title"]));

		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = $_SWIFT["language"]["templatename"];
		$colarray[1]["align"] = "center";
		$colarray[1]["nowrap"] = true;
		$colarray[1]["value"] = $_SWIFT["language"]["compiletime"];
		$colarray[2]["align"] = "center";
		$colarray[2]["nowrap"] = true;
		$colarray[2]["value"] = $_SWIFT["language"]["status"];
		printDataRow($colarray, "tabletitlerow");

		$dbCore->query("SELECT `templateid`, `name`, `modified` FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` = '". intval($_POST["tgroupid"]) ."' ORDER BY `templateid` ASC;");
		while ($dbCore->nextRecord())
		{
			// Try to compile this template
			$result = $template->displayRawTemplate($dbCore->Record["name"]);

			if (!$result["status"])
			{
				$diagnosestatusimg = "icon_failure.gif";
				$diagnosetext = $_SWIFT["language"]["failure"];
			} else {
				$diagnosestatusimg = "icon_success.gif";
				$diagnosetext = $_SWIFT["language"]["success"];
			}

			$colarray = array();
			$colarray[0]["align"] = "left";
			$colarray[0]["nowrap"] = true;
			$colarray[0]["value"] = '<a href="'. $_SWIFT["swiftpath"] .'admin/index.php?_m=core&_a=edittemplate&templateid='. $dbCore->Record["templateid"] .'&tgroupid='. intval($_POST["tgroupid"]) .'">'.$dbCore->Record["name"]."</a>";

			$colarray[1]["align"] = "center";
			$colarray[1]["nowrap"] = true;
			$colarray[1]["value"] = number_format($result["compiletime"], 2).'&nbsp;'.$_SWIFT["language"]["seconds"];

			$colarray[2]["align"] = "center";
			$colarray[2]["nowrap"] = true;
			$colarray[2]["value"] = '<img src="'. $_SWIFT["themepath"].$diagnosestatusimg .'" border="0" />&nbsp;'.$diagnosetext.'';

			printDataRow($colarray, getRowBG());
		}

		printMainTableFooter();
		$template->assign("backurl", "index.php?_m=core&_a=templatediagnostics");
	} else {
		// ======= LIST MODIFIED TEMPLATES =======
		printFormStart("modifiedform", "index.php", "POST", true);
		printMainTableHeader($_SWIFT["language"]["listmodified"]);

		$index = 0;
		foreach ($_SWIFT["tgroupcache"] as $key=>$val)
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["tgroupid"];
			$index++;
		}

		printSelectRow("tgroupid", $_SWIFT["language"]["moditgroup"], $_SWIFT["language"]["desc_moditgroup"], $options);

		printSubmitRow($_SWIFT["language"]["list"]);

		printMainTableFooter();

		addHiddenField("_m", "core");
		addHiddenField("_a", "templatediagnostics");
		addHiddenField("listmodified", "1");
		printFormEnd();


		// ======= DIAGNOSE SMARTY ERRORS =======
		echo "<BR />";
		printFormStart("diagnoseform", "index.php", "POST", true);
		printMainTableHeader($_SWIFT["language"]["diagnosesmarty"]);

		printSelectRow("tgroupid", $_SWIFT["language"]["diagtgroup"], $_SWIFT["language"]["desc_diagtgroup"], $options);

		printSubmitRow($_SWIFT["language"]["diagnose"]);

		printMainTableFooter();

		addHiddenField("_m", "core");
		addHiddenField("_a", "templatediagnostics");
		addHiddenField("diagnose", "1");
		printFormEnd();
		$template->assign("backurl", "index.php?_m=core&_a=managetemplates");
	}

	
	$interface->adminFooter();






/**
* ###############################################
* LOGINSHARE
* ###############################################
*/
} else if ($eventaction == "manageloginshare") {
	require_once ("./includes/LoginShare/loginshare.config.php");

	if ($_REQUEST["do"] == "loginmodule" && isset($_LOGINAPI[$_REQUEST["loginmoduleid"]]))
	{
		$_loginapimodule = $_LOGINAPI[$_REQUEST["loginmoduleid"]];
		require_once ("./includes/LoginShare/".$_loginapimodule["include"]);
		$forms = renderLoginShareForm();

		if ($_POST["step"] == "1" && $_SWIFT["isdemo"] == true)
		{
			header("location: index.php?_m=core&_a=manageloginshare");
			exit;
		} else if ($_POST["step"] == "1" && $_SWIFT["isdemo"] != true) {
			foreach ($forms as $key=>$val)
			{
				$settings->updateKey("loginshare", $val["name"], $_POST[$val["name"]]);
			}
			header("location: index.php?_m=core&_a=manageloginshare");
			exit;
		}
		if (empty($_POST["step"]))
		{
			$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["loginshare"], 1);

			$interface->adminNavBar('<a href="index.php?_m=core&_a=managetemplategroups" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=manageloginshare" title="'.$_SWIFT["language"]["loginshare"].'">'.$_SWIFT["language"]["loginshare"].'</a>', $_SWIFT["language"]["desc_loginshare"] , 0);

			printInfoBox($infomessage);
			printErrorBox($errormessage);

			printFormStart("loginshareform");
			printMainTableHeader($_loginapimodule["title"]);
			foreach ($forms as $key=>$val)
			{
				printTextRow($val["name"], $val["title"], "", "text", $settings->getKey("loginshare", $val["name"]));
			}
			printSubmitRow($_SWIFT["language"]["update"]);
			printMainTableFooter();
			addHiddenField("_m", "core");
			addHiddenField("_a", "manageloginshare");
			addHiddenField("do", "loginmodule");
			addHiddenField("step", "1");
			addHiddenField("loginmoduleid", $_REQUEST["loginmoduleid"]);
			printFormEnd();

			$template->assign("backurl", "index.php?_m=core&_a=manageloginshare");
		}

	} else {
		$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["loginshare"], 1);

		$interface->adminNavBar('<a href="index.php?_m=core&_a=managetemplategroups" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=manageloginshare" title="'.$_SWIFT["language"]["loginshare"].'">'.$_SWIFT["language"]["loginshare"].'</a>', $_SWIFT["language"]["desc_loginshare"] , 0);

		printInfoBox($infomessage);
		printErrorBox($errormessage);

		// ======= LISTING =======
		printMainTableHeader($_SWIFT["language"]["pluginlist"]);

		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = $_SWIFT["language"]["ls_module"];
		$colarray[1]["width"] = "150";
		$colarray[1]["value"] = $_SWIFT["language"]["options"];
	
		printDataRow($colarray, "tabletitlerow");

		foreach ($_LOGINAPI as $key=>$val)
		{
			$colarray[0]["align"] = "left";
			$colarray[0]["nowrap"] = true;
			$colarray[0]["value"] = '<a href="index.php?_m=core&_a=manageloginshare&do=loginmodule&loginmoduleid='. $key .'" title="'. $_SWIFT["language"]["settings"] .'"><img src="'. $_SWIFT["themepath"] .'icon_loginshare.gif" border="0"> '.$val["title"].'</a>';
			$colarray[1]["width"] = "150";
			$colarray[1]["value"] = '<a href="index.php?_m=core&_a=manageloginshare&do=loginmodule&loginmoduleid='. $key .'" title="'. $_SWIFT["language"]["settings"] .'"><img src="'. $_SWIFT["themepath"] .'icon_settings.gif" border="0">&nbsp;'.$_SWIFT["language"]["settings"].'</a>';
		
			printDataRow($colarray);
		}

		printMainTableFooter();

		$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	}

	$interface->adminFooter();





/**
* ###############################################
* SEARCH TEMPLATES
* ###############################################
*/
} else if ($eventaction == "searchtemplates") {
	$interface->adminHeader($_SWIFT["language"]["templates"]." > ".$_SWIFT["language"]["search"], 1);

	$interface->adminNavBar('<a href="index.php?_m=core&_a=dashboard" title="'.$_SWIFT["language"]["dashboard"].'">'.$_SWIFT["language"]["dashboard"].'</a> &raquo; <a href="index.php?_m=core&_a=managetemplates" title="'.$_SWIFT["language"]["templates"].'">'.$_SWIFT["language"]["templates"].'</a> &raquo; <a href="index.php?_m=core&_a=searchtemplates" title="'.$_SWIFT["language"]["search"].'">'.$_SWIFT["language"]["search"].'</a>', $_SWIFT["language"]["desc_templates"] , 0);

	printInfoBox($infomessage);
	printErrorBox($errormessage);


	if ($_POST["step"] == 1 && !empty($_POST["searchquery"]))
	{
		require_once ("./includes/functions_sqlsearch.php");

		printMainTableHeader(sprintf($_SWIFT["language"]["searchqueryd"], htmlspecialchars($_POST["searchquery"])));

		$colarray[0]["align"] = "left";
		$colarray[0]["nowrap"] = true;
		$colarray[0]["value"] = $_SWIFT["language"]["templatename"];
		$colarray[1]["align"] = "center";
		$colarray[1]["nowrap"] = true;
		$colarray[1]["value"] = $_SWIFT["language"]["status"];
		printDataRow($colarray, "tabletitlerow");

		$dbCore->query("SELECT templates.templateid, templates.name, templates.modified FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) WHERE templates.tgroupid = '". intval($_POST["tgroupid"]) ."' AND ((". buildSQLSearch("templatedata.contents", $_POST["searchquery"]) .") OR (". buildSQLSearch("templates.name", $_POST["searchquery"]) .")) ORDER BY templates.templateid ASC;");
		while ($dbCore->nextRecord())
		{
			if ($dbCore->Record["modified"] == MODIFIED_NONE) {
				$modifiedstatus = "icon_templatenotmodified.gif";
				$modifiedtext = $_SWIFT["language"]["notmodified"];
			} else if ($dbCore->Record["modified"] == MODIFIED_UPGRADE) {
				$modifiedstatus = "icon_templateupgrade.gif";
				$modifiedtext = $_SWIFT["language"]["upgrade"];
			} else {
				$modifiedstatus = "icon_templatemodified.gif";
				$modifiedtext = $_SWIFT["language"]["modified"];
			}

			$colarray = array();
			$colarray[0]["align"] = "left";
			$colarray[0]["nowrap"] = true;
			$colarray[0]["value"] = '<a href="'. $_SWIFT["swiftpath"] .'admin/index.php?_m=core&_a=edittemplate&templateid='. $dbCore->Record["templateid"] .'&tgroupid='. intval($_POST["tgroupid"]) .'">'.$dbCore->Record["name"]."</a>";

			$colarray[1]["align"] = "center";
			$colarray[1]["nowrap"] = true;
			$colarray[1]["value"] = '<img src="'. $_SWIFT["themepath"].$modifiedstatus .'" border="0" />&nbsp;'.$modifiedtext .'';
			$colarray[1]["width"] = 250;

			printDataRow($colarray, getRowBG());
		}

		printMainTableFooter();

		echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .'<img src="'. $_SWIFT["themepath"] .'icon_templatemodified.gif" border="0" /> '. $_SWIFT["language"]["modified"] .'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_templateupgrade.gif" border="0" /> '. $_SWIFT["language"]["upgrade"] .'&nbsp;&nbsp;&nbsp;';
		$template->assign("backurl", "index.php?_m=core&_a=templatediagnostics");
	} else {
		printFormStart();
		printMainTableHeader($_SWIFT["language"]["searchtemplates"]);

		printTextRow("searchquery", $_SWIFT["language"]["query"], $_SWIFT["language"]["desc_query"], "text", $_POST["searchquery"]);

		unset($options);
		$index = 0;
		foreach ($_SWIFT["tgroupcache"] as $key=>$val)
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["tgroupid"];
			$index++;
		}

		printSelectRow("tgroupid", $_SWIFT["language"]["searchtgroup"], $_SWIFT["language"]["desc_searchtgroup"], $options);

		printSubmitRow($_SWIFT["language"]["search"]);

		printMainTableFooter();

		addHiddenField("_m", "core");
		addHiddenField("_a", "searchtemplates");
		addHiddenField("step", "1");
		printFormEnd();

		$template->assign("backurl", "index.php?_m=core&_a=managetemplategroups");
	}

	$interface->adminFooter();

}


?>